package com.dcivision.setup.web;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsSendEmail;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.GenericAddress;
import com.dcivision.framework.notification.EmailDeliveryMessage;
import com.dcivision.framework.notification.NotificationWay;
import com.dcivision.framework.notification.NotificationWayFactory;
import com.dcivision.framework.web.AbstractListAction;
import com.dcivision.framework.web.AbstractSearchForm;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;

public class ListPasswordAction extends AbstractListAction {

	public final static String VAR_USER_GROUP_LIST = "varUserGroupList";

	public final static String VAR_USER_ROLE_LIST = "varUserRoleList";

	public ListPasswordAction() {
		super();
		this.setListName("passwordList");
	}

	public String getFunctionCode() {
		return SystemFunctionConstant.STP_PASSWORD;
	}

	public String getMajorDAOClassName() {
		return "com.dcivision.user.dao.UserRecordDAObject";
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		// super.execute(mapping,form,request,response);
		ListPasswordForm passwordForm = (ListPasswordForm) form;
		if (SystemFunctionConstant.STP_PASSWORD
				.equals(passwordForm.getOpMode())) {
			try {
				this.updateListData(mapping, passwordForm, request, response);
				this.getConnection(request).commit();
				this.addMessage(request,"common.message.record_updated");
				passwordForm.reset(mapping,request);
			} catch (SQLException ex){
        log.error(ex, ex);
			}
			
		} else if ("STP_PASSWORD_ALL"
				.equals(passwordForm.getOpMode())){
			try{
				this.updateAll(mapping, passwordForm, request, response);
				this.getConnection(request).commit();
				this.addMessage(request,"common.message.record_updated");
				passwordForm.reset(mapping,request);
			}catch (SQLException ex){
        log.error(ex, ex);
			}
			passwordForm.setOpMode("");
		}
		return super.execute(mapping, form, request, response);
	}

	/**
	 * getListData
	 * 
	 * Override the parent's function. Since it required to get the user role
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @throws ApplicationException
	 */
	public void getListData(ActionMapping mapping, AbstractSearchForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws ApplicationException {
		super.getListData(mapping, form, request, response);

		// Get the user groups and user roles of each user record.
		List listResult = (ArrayList) request.getAttribute(this.getListName());
		List listRole = new ArrayList();
		List listGroup = new ArrayList();

		request.setAttribute("myFlag", request.getParameter("pageFlag"));

		UserRoleDAObject userRoleDAO = new UserRoleDAObject(this
				.getSessionContainer(request), this.getConnection(request));
		UserGroupDAObject userGroupDAO = new UserGroupDAObject(this
				.getSessionContainer(request), this.getConnection(request));
		for (int i = 0; i < listResult.size(); i++) {
			UserRecord userRecord = (UserRecord) listResult.get(i);
			listRole.add(userRoleDAO.getListByUserRecordID(userRecord.getID()));
			listGroup.add(userGroupDAO.getListByUserRecordIDGroupType(
					userRecord.getID(), UserGroup.GROUP_TYPE_PUBLIC));
		}
		request.setAttribute(VAR_USER_ROLE_LIST, listRole);
		request.setAttribute(VAR_USER_GROUP_LIST, listGroup);

		if (!Utility.isEmpty(request.getParameter("index"))) {
			request.setAttribute("index", request.getParameter("index"));
		}
	}

	public void updateListData(ActionMapping mapping, AbstractSearchForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws ApplicationException {
		ListPasswordForm passwordForm = (ListPasswordForm) form;
		SessionContainer sessionContainer = this.getSessionContainer(request);
		Connection conn = this.getConnection(request);
		UserRecordDAObject userDAO = new UserRecordDAObject(sessionContainer,
				conn);
		UserRecord userRecord = new UserRecord();
		if (form.getBasicSelectedID() != null) {
			for (int i = 0; i < form.getBasicSelectedID().length; i++) {
				Integer userRecordID = TextUtility.parseIntegerObj(form
						.getBasicSelectedID()[i]);
				userRecord = (UserRecord) userDAO.getUserByID(userRecordID);

				if (!Utility.isEmpty(passwordForm.getPwdExpiryDay())
						&& passwordForm.getPwdExpiryDay() != null) {
					userRecord.setPwdExpiryDay(TextUtility
							.parseIntegerObj(passwordForm.getPwdExpiryDay()));
				}
				if (!Utility.isEmpty(passwordForm.getLoginPwd())
						&& passwordForm.getLoginPwd() != null) {
					userRecord.setLoginPwd(passwordForm.getLoginPwd());
				}
				if (!Utility.isEmpty(passwordForm.getMaxAttempt())
						&& passwordForm.getMaxAttempt() != null) {
					userRecord.setMaxAttempt(TextUtility
							.parseIntegerObj(passwordForm.getMaxAttempt()));
				}

					userDAO.updateObject(userRecord);
//					conn.commit();
					if ("true".equals(passwordForm.getSendMail())){
						String recipients = userRecord.getEmail();
						String subject = "new password";
						String emailContent = "Dear " + userRecord.getFullName() + "\n" + "new password is " + passwordForm.getLoginPwd();
						DmsSendEmail email = new DmsSendEmail();
			      email.setSender(UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID()));
			      email.setRecipients(recipients);
			      email.setSubject(subject);
			      email.setContent(emailContent);
			      this.sendEmail(request,email);
					}				
			}
		}

	}
	
	public void updateAll(ActionMapping mapping, AbstractSearchForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws ApplicationException {
		ListPasswordForm passwordForm = (ListPasswordForm) form;
		SessionContainer sessionContainer = this.getSessionContainer(request);
		Connection conn = this.getConnection(request);
		UserRecordDAObject userDAO = new UserRecordDAObject(sessionContainer,
				conn);
		List userList = userDAO.getListAll(passwordForm);
		UserRecord userRecord = new UserRecord();
		if (userList != null) {
			for (int i = 0; i < userList.size(); i++) {
				userRecord = (UserRecord)userList.get(i);
				Integer userRecordID = userRecord.getID();
				userRecord = (UserRecord) userDAO.getUserByID(userRecordID);

				if (!Utility.isEmpty(passwordForm.getPwdExpiryDay())
						&& passwordForm.getPwdExpiryDay() != null) {
					userRecord.setPwdExpiryDay(TextUtility
							.parseIntegerObj(passwordForm.getPwdExpiryDay()));
				}
				if (!Utility.isEmpty(passwordForm.getLoginPwd())
						&& passwordForm.getLoginPwd() != null) {
					userRecord.setLoginPwd(passwordForm.getLoginPwd());
				}
				if (!Utility.isEmpty(passwordForm.getMaxAttempt())
						&& passwordForm.getMaxAttempt() != null) {
					userRecord.setMaxAttempt(TextUtility
							.parseIntegerObj(passwordForm.getMaxAttempt()));
				}

					userDAO.updateObject(userRecord);
//					conn.commit();
					
					if ("true".equals(passwordForm.getSendMail())){
						String recipients = userRecord.getEmail();
						String subject = "new password";
						String emailContent = "Dear " + userRecord.getFullName() + "\n" + "new password is " + passwordForm.getLoginPwd();
						DmsSendEmail email = new DmsSendEmail();
			      email.setSender(UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID()));
			      email.setRecipients(recipients);
			      email.setSubject(subject);
			      email.setContent(emailContent);
			      this.sendEmail(request,email);
					}					
			}
		}

	}
	
  public String sendEmail(HttpServletRequest request, DmsSendEmail email){
    String state = "";
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);

    try {
      // create an email
      EmailDeliveryMessage msg = new EmailDeliveryMessage();

      String curUserEmail = UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID());
      if (Utility.isEmpty(curUserEmail)) {
        curUserEmail = SystemParameterFactory.getSystemParameter(SystemParameterConstant.SMTP_ADMIN_ADDRESS);
      }
      String curUserName = UserInfoFactory.getUserFullName(sessionContainer.getUserRecordID());
      if (Utility.isEmpty(curUserName)) {
        curUserName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.SMTP_ADMIN_NAME);
      }
      //bill add for EIP-1567
      msg.setSender(new GenericAddress("", curUserName,"utf-8"));

      String[] toRecipients = TextUtility.splitString(email.getRecipients(), ";");
      for (int i = 0; i < toRecipients.length; ++i) {
        msg.addToRecipient(new GenericAddress(toRecipients[i]));
      }
      if (!Utility.isEmpty(email.getCCRecipients())) {
        String[] ccRecipients = TextUtility.splitString(email.getCCRecipients(), ";");
        for (int i = 0; i < ccRecipients.length; ++i) {
          msg.addCCRecipient(new GenericAddress(ccRecipients[i]));
        }
      }
      if (!Utility.isEmpty(email.getBCCRecipients())) {
        String[] bccRecipients = TextUtility.splitString(email.getBCCRecipients(), ";");
        for (int i = 0; i < bccRecipients.length; ++i) {
          msg.addBCCRecipient(new GenericAddress(bccRecipients[i]));
        }
      }
      msg.setCharset(SystemParameterFactory.getSystemParameter(SystemParameterConstant.ENCODING));
      msg.setSubject(email.getSubject());
      msg.setMailContent(email.getContent());

      // send email
      NotificationWay emailNotification = NotificationWayFactory.getNotificationInstance(NotificationWay.EMAIL_NOTIFICATION_INSTANCE);
      emailNotification.addDeliveryMessage( msg);
      emailNotification.send();
      state=DmsOperationConstant.EMAIL_SENT;
      log.debug("---------------Message Send Successfully--------------------");

    } catch (UnsupportedEncodingException unsee) {
      log.error("Error when send email attachment - UnsupportedEncodingException", unsee);
    } catch (Exception e) {
      log.error("Error when send email attachment", e);
    } 
    return state;
  }

}
